<?php
/*
 * 前端默认控制器
 */
class IndexController extends BasicController {
    
    public $email;

    private function init(){}

    /*
    * 默认控制器 
    * 函数传参测试
    * http://www.yof.local/default/index/index/b/vvv/a/zzz
    */
    public function indexAction($a = '柴', $b = '炜'){
        echo '你好：'.$a.$b;
    }
    
    /*
    * 直播视频录入
    */
    public function swoolelivecameraAction(){
    	//直播视频录入
//        Yaf_Dispatcher::getInstance()->autoRender(FALSE);
        $this->display("swoolelivecamera");
    }
    
    /*
    * 直播视频接收
    */
    public function swooleliveAction(){
    	//直播视频接受
//        Yaf_Dispatcher::getInstance()->autoRender(FALSE);
        $this->display("swoolelive");
    }
    
    /*
    * swoolesocket
    */
    public function swoolesocketAction($rid = 0, $uid = 0){
        $assign['rid'] = $rid;
        $assign['uid'] = $uid;
        $this->display("swoolesocket", $assign);
    }
    
    public function uploadimgAction(){
        $imageModel = $this->load('Images');
        $res = ["status" => 1, "msg" => "", "img" => ""];
        $salt = rand(1, 9999);
        $fileName = '';//保存名称
        
        $allowed_types = ['png', 'gif', 'jpg'];
        
        $res['msg'] = "上传失败";
        $path = APP_PATH.'/public/uploads/';
        
        if(mkdirs($path)){
            $salt = rand(1, 9999);
            $fileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);//获取后缀
            $fileName = time().'_'.$salt.'.'.$fileType;//保存名称
            if(in_array($fileType, $allowed_types)){
                if(@move_uploaded_file($_FILES['file']['tmp_name'], $path.$fileName)){
                    if($fileType == "png"){
                        $im = ImageCreateFromPNG($path.$fileName);//参数是图片的存方路径
                    }
                    elseif($fileType == "jpeg" || $fileType == "jpg"){
                        $im = ImageCreateFromJPEG($path.$fileName);//参数是图片的存方路径
                    }
                    elseif($fileType == "gif"){
                        $im = ImageCreateFromGIF($path.$fileName);//参数是图片的存方路径
                    }
                    
                    $imageModel->imagecropper($im, 529, 296, $path.$fileName, $fileType);//调用上面的函数
                    $res['img'] = $fileName;
                    $res['status'] = 0;
                    $res['msg'] = "上传成功";
                }
            }
            else{
                $res['msg'] = "请检查上传文件格式";
            }
        }
        
        echo json_encode($res);
        return false;
    }
    
    /*
    * yar测试
    */
    public function yarAction(){
        $p['phone'] = '18357132456';
        $p['data'] = '您有新的报修信息，故障简述：【变量】，终端类型：【变量】，联系人：【变量】，所属公司：【变量】，联系电话：【变量】';

        $res = $this->yarRequest(API_URL.'/yarServer/api', 'sendsms', $p);
        P($res);
    }
    
    /*
    * 短信相关测试
    */
    public function smsAction(){
        //引入相关操作文件
        Helper::import('Sms');
        
        $phone = '18357132456';
        echo getIcode($phone);
        
    }
    
    /*
    * mongo相关测试
    */
    public function mongotestAction(){
        Yaf_Loader::import(LIB_PATH.'/Cmongo.php');
        
        $m = new Cmongo();
        
//        $res = $m->getAll('User');//一次性获取整张表的数据
//        $res = $m->getAll('User', ['key' => 't_key_5']);//带查询条件一次性获取所有数据
//        $res = $m->getOne('User', ['key' => 't_key_6']);//带查询条件获取唯一一条数据 如果没有该数据的话返回NULL
//        $cnt = $m->getCount('User', ['key' => 't_key_5']);//获取指定条件的数量
//        $r = $m->toDelete('User', ['key' => 't_key_5']);//删除指定key值的数据
        
//        $salt = time();
        
//        $r = $m->toInsert('User', ['key' => 't_key_'.$salt, 'val' => '11111', 'ctime' => $salt]);//新增操作
//        $r = $m->toUpdate('User', ['key' => 't_key_5'], ['val' => '22222', 'ctime' => time()]);//更新操作

//        $r = $m->getAll('User', ['ctime' => ['$gt' => 1494831984]]);//大于
//        $r = $m->getAll('User', ['ctime' => ['$gte' => 1494831984]]);//大于等于
//        $r = $m->getAll('User', ['ctime' => ['$lt' => 1494831984]]);//小余等于
//        $r = $m->getAll('User', ['ctime' => ['$lte' => 1494831984]]);//小余等于
//        $r = $m->getAll('User', ['ctime' => ['$gte' => 1494831984, '$lte' => time()]]);//大于1494831984 小余当前
//        $r = $m->getAll('User', ['ctime' => ['$ne' => 1494831984]]);//不等于
        
//        $r = $m->getAll('User', ['key' => ['$in' => ['t_key_2', 't_key_3']]]);//in 操作
//        $r = $m->getAll('User', ['key' => ['$nin' => ['t_key_2', 't_key_3']]]);//not in 操作
        
//        $r = $m->getAll('User', ['key' => new MongoRegex('/.*t_key.*/i')]);//like 操作
        
//        P($r);
        P($res);
    }
    
    /*
    * 邮件相关测试
    */
    public function mailAction(){
        
        Yaf_Loader::import(LIB_PATH.'/Email.php');
        $this->email = new Email();
        
        $config['protocol'] = 'smtp';
        $config['smtp_host'] = SMTP_HOST;
        $config['smtp_user'] = SMTP_USER;
        $config['smtp_pass'] = SMTP_PASS;
        $config['mailtype'] = 'html';
        $config['validate'] = true;
        $config['priority'] = 1;
        $config['crlf']  = "\r\n";
        $config['smtp_port'] = 25;
        $config['charset'] = 'utf-8';
        $config['wordwrap'] = TRUE;

        $this->email->initialize($config);
        $this->email->subject('测试YAF邮件');
        $this->email->from(SMTP_USER, 'YAF');
        $this->email->to('402848317@qq.com');

        $this->email->message('有新用户提交开通申请！请及时处理！');
        $this->email->send();
    }
    
    public function exportAction(){
        $testModel = $this->load('Test');
        $res = $testModel->Select();
        
        $filename = 'aaa.xls';
        $titles = ['考号', '姓名', '总分'];
        $data = [];
        
        if(!empty($res) && is_array($res)){
            foreach ($res as $k => $item) {
                $data[$k] = [
                    0 => isset($item['t_kaohao']) ? $item['t_kaohao'] : '',
                    1 => isset($item['t_name']) ? $item['t_name'] : '',
                    2 => isset($item['t_total']) ? $item['t_total'] : ''
                ];
            }
        }
        
        @error_reporting(E_ERROR | E_PARSE); 
        header("Content-Type: application/vnd.ms-excel");
        header("Accept-Ranges:bytes");
        header("Content-Disposition:attachment;filename={$filename}.xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        //输出头信息
        echo '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="expires" content="Mon, 06 Jan 1999 00:00:01 GMT"><meta http-equiv=Content-Type content="text/html; charset=utf-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name></x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>';
        echo '<table>';
        //拼接第一行字段信息
        echo '<tr>';
        if(!empty($titles) && is_array($titles)){
            foreach ($titles as $v) {
                echo '<th>'.$v.'</th>';
            }
        }
        echo '</tr>';
        unset($titles);
        if(!empty($data) && is_array($data)){
            foreach($data as $k => $v){
                echo '<tr>';
                if(!empty($v) && is_array($v)){
                    foreach ($v as $item) {
                        echo '<td style="vnd.ms-excel.numberformat:@">'.$item.'</td>';
                    }
                }
                echo '</tr>';
            }
            unset($data[$k]);
        }
        
        echo '</table>';
        
        
//        Yaf_Loader::import(LIB_PATH.'/PHPExcel.php');
//        Yaf_Loader::import(LIB_PATH.'/PHPExcel/Writer/IWriter.php');
//        Yaf_Loader::import(LIB_PATH.'/PHPExcel/Writer/Excel5.php');
//        Yaf_Loader::import(LIB_PATH.'/PHPExcel/IOFactory.php');
//        
//        $resultPHPExcel = new PHPExcel();
//        
//        $resultPHPExcel->getActiveSheet()->setCellValue('A1', '考号');
//        $resultPHPExcel->getActiveSheet()->setCellValue('B1', '姓名');
//        $resultPHPExcel->getActiveSheet()->setCellValue('C1', '总分');
//        
//        $i = 2;
//        foreach($data as $item){
//            $resultPHPExcel->getActiveSheet()->setCellValue('A'.$i, $item['t_kaohao']);
//            $resultPHPExcel->getActiveSheet()->setCellValue('B'.$i, $item['t_name']);
//            $resultPHPExcel->getActiveSheet()->setCellValue('C'.$i, $item['t_total']);
//            $i ++;
//        } 
//        
//        $outputFileName = 'total.xls';
//        $xlsWriter = new PHPExcel_Writer_Excel5($resultPHPExcel);
//        header("Content-Type: application/force-download");
//        header("Content-Type: application/octet-stream");
//        header("Content-Type: application/download");
//        header('Content-Disposition:inline;filename="'.$outputFileName.'"');
//        header("Content-Transfer-Encoding: binary");
//        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
//        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
//        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
//        header("Pragma: no-cache");
//        $xlsWriter->save('php://output'); 
//        exit;
    }
    
    /*
    * 四中成绩计算 -- 读xls
    */
    public function xlsAction(){
        
        Yaf_Loader::import(LIB_PATH.'/PHPExcel.php');
        $reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
        
        $PHPExcel = $reader->load(APP_PATH."/public/file/gao.xls"); // 载入excel文件
        $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumm = $sheet->getHighestColumn(); // 取得总列数

        /** 循环读取每个单元格的数据 */
        for ($row = 1; $row <= $highestRow; $row++){//行数是以第1行开始
            for ($column = 'A'; $column <= $highestColumm; $column++) {//列数是以A列开始
                $dataset[$row][] = $sheet->getCell($column.$row)->getValue();
//                echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."<br />";
            }
        }
        
        //////////////////读取完毕///////////////////////
        
        unset($dataset[1]);
//        if(!empty($dataset) && is_array($dataset)){
//            $testModel = $this->load('Test');
//            
//            foreach ($dataset as $item) {
//                $data['t_class'] = $item[0];
//                $data['t_kaohao'] = $item[1];
//                $data['t_name'] = $item[2];
//                
//                $data['t_wlx'] = $item[3];
//                $data['t_hxx'] = $item[4];
//                $data['t_swx'] = $item[5];
//                $data['t_zzx'] = $item[6];
//                $data['t_lsx'] = $item[7];
//                $data['t_dlx'] = $item[8];
//                $data['t_jsx'] = $item[9];
//                
//                $data['t_yuwen'] = $item[10] == '缺考' ? 0 : $item[10];
//                $data['t_shuxue'] = $item[11] == '缺考' ? 0 : $item[11];
//                $data['t_yingyu'] = $item[12] == '缺考' ? 0 : $item[12];
//                $data['t_wuli'] = $item[13] == '缺考' ? 0 : $item[13];
//                $data['t_huaxue'] = $item[14] == '缺考' ? 0 : $item[14];
//                $data['t_shengwu'] = $item[15] == '缺考' ? 0 : $item[15];
//                $data['t_lishi'] = $item[16] == '缺考' ? 0 : $item[16];
//                $data['t_dili'] = $item[17] == '缺考' ? 0 : $item[17];
//                $data['t_zhengzhi'] = $item[18] == '缺考' ? 0 : $item[18];
//                $data['t_jishu1'] = $item[19] == '缺考' ? 0 : $item[19];
//                $data['t_jishu2'] = $item[20] == '缺考' ? 0 : $item[20];
//                
//                $total = 0;
//                
//                $total = $data['t_yuwen'] + $data['t_shuxue'] + $data['t_yingyu'];
//                
//                if($data['t_wlx']){
//                    $total += $data['t_wuli'];
//                }
//                if($data['t_hxx']){
//                    $total += $data['t_huaxue'];
//                }
//                if($data['t_swx']){
//                    $total += $data['t_shengwu'];
//                }
//                if($data['t_zzx']){
//                    $total += $data['t_zhengzhi'];
//                }
//                if($data['t_lsx']){
//                    $total += $data['t_lishi'];
//                }
//                if($data['t_dlx']){
//                    $total += $data['t_dili'];
//                }
//                if($data['t_jsx']){
//                    $total += $data['t_jishu1'] + $data['t_jishu2'];
//                }
//                
//                $data['t_total'] = $total;
////                P($data);
//                $data['mtime'] = CUR_TIMESTAMP;
//
//                $testModel->Insert($data);
//            }
//        }
        
        P($dataset);
        return false;
    }
    
}